<template>
  <div class="app-container">
    <div v-if="user">
      <el-row :gutter="20">
        <el-col :span="6" :xs="24">
          <user-card :user="user" @editProfile="showEditCol" />
        </el-col>
        <transition name="fade-transform">
          <el-col
            :span="12"
            :xs="24"
            v-if="['baseInfo', 'email', 'password'].includes(editStatus)"
          >
            <el-card>
              <div class="edit-content">
                <template v-if="editStatus === 'baseInfo'">
                  <el-form
                    key="baseInfo"
                    :ref="editStatus"
                    :rules="baseInfoRules"
                    :model.sync="baseInfo"
                  >
                    <el-form-item label="用户名" prop="username">
                      <el-input
                        v-model.trim="baseInfo.username"
                        placeholder="请填写用户名"
                      />
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                      <el-input
                        v-model.trim="baseInfo.mobile"
                        placeholder="请填写手机号"
                      />
                    </el-form-item>
                    <el-form-item label="备注">
                      <el-input
                        type="textarea"
                        autosize
                        v-model.trim="baseInfo.remark"
                        placeholder="请填写备注"
                      />
                    </el-form-item>
                  </el-form>
                </template>
                <template v-else-if="editStatus === 'email'">
                  <el-form
                    key="email"
                    :ref="editStatus"
                    :rules="emailRules"
                    :model.sync="email"
                  >
                    <el-form-item label="邮箱" prop="email">
                      <el-input
                        v-model.trim="email.email"
                        placeholder="请填写邮箱"
                      />
                    </el-form-item>
                  </el-form>
                </template>
                <template v-else>
                  <el-form
                    key="password"
                    :ref="editStatus"
                    :rules="passwordRules"
                    :model.sync="password"
                  >
                    <el-form-item label="旧密码" prop="old_password">
                      <el-input
                        type="password"
                        v-model="password.old_password"
                        placeholder="旧密码"
                      />
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_password">
                      <el-input
                        type="password"
                        v-model="password.new_password"
                        placeholder="新密码"
                      />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="retype_password">
                      <el-input
                        type="password"
                        v-model="password.retype_password"
                        placeholder="确认密码"
                      />
                    </el-form-item>
                  </el-form>
                </template>
                <div class="update-button">
                  <el-button
                    v-waves
                    class="filter-item"
                    type="primary"
                    icon="el-icon-close"
                    @click="editStatus = ''"
                  >
                    取消
                  </el-button>
                  <el-button
                    v-waves
                    class="filter-item"
                    type="primary"
                    icon="el-icon-finished"
                    @click="handleupDateProfile"
                  >
                    完成
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </transition>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { Form } from 'element-ui'
import { UserModule } from '@/store/modules/user'
import UserCard from './components/UserCard.vue'
import { isValidMobile, isValidEmail } from '@/utils/validate'
import {
  profileUserUpdate,
  profileUserChangePassword,
  profileUserChangeEmail
} from '@/api/system/profile'
export interface IProfile {
  name: string
  email: string
  avatar: string
  remark: string
  status: number
}

@Component({
  name: 'Profile',
  components: {
    UserCard
  }
})
export default class extends Vue {
  private validateMobile = (rule: any, value: string, callback: Function) => {
    if (!isValidMobile(value)) {
      callback(new Error('请输入正确的手机号码'))
    } else {
      callback()
    }
  }
  private validatePassword = (rule: any, value: string, callback: Function) => {
    if (typeof value === 'string' && value.length < 6) {
      callback(new Error('密码不能低于6位'))
    } else {
      callback()
    }
  }
  private validateRetypePassword = (
    rule: any,
    value: string,
    callback: Function
  ) => {
    if (typeof value === 'string' && value.length < 6) {
      callback(new Error('密码不能低于6位'))
    } else if (
      value !== ((this.$refs['password'] as Form).model as any).new_password
    ) {
      callback(new Error('密码输入不一致'))
    } else {
      callback()
    }
  }
  private emailRules = {
    email: [
      {
        required: true,
        type: 'email',
        message: '请输入正确的邮箱',
        trigger: 'blur'
      }
    ]
  }
  private passwordRules = {
    old_password: [
      {
        required: true,
        validator: this.validatePassword,
        trigger: 'blur'
      }
    ],
    new_password: [
      {
        required: true,
        validator: this.validatePassword,
        trigger: 'blur'
      }
    ],
    retype_password: [
      {
        required: true,
        validator: this.validateRetypePassword,
        trigger: 'blur'
      }
    ]
  }
  private baseInfoRules = {
    username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
    mobile: [
      { required: true, validator: this.validateMobile, trigger: 'blur' }
    ]
  }
  private editStatus = ''
  get user() {
    return {
      username: UserModule.username,
      name: UserModule.name,
      email: UserModule.email,
      avatar: UserModule.avatar,
      remark: UserModule.remark,
      status: UserModule.status,
      mobile: UserModule.mobile
    }
  }
  private baseInfo = {
    username: '',
    mobile: '',
    remark: ''
  }
  private email = {
    email: ''
  }
  private password = {
    old_password: '',
    new_password: '',
    retype_password: ''
  }
  @Watch('user')
  onUserChange(value: any) {
    this.baseInfo.mobile = this.user.mobile
    this.baseInfo.remark = this.user.remark
    this.email.email = this.user.email
  }
  private showEditCol(str: string) {
    this.editStatus = str
    this.resetData()
    /* this.$nextTick(() => {
      ;(this.$refs[this.editStatus] as Form).clearValidate()
    }) */
  }
  private async handleupDateProfile() {
    ;(this.$refs[this.editStatus] as Form).validate(async valid => {
      if (valid) {
        try {
          if (this.editStatus === 'baseInfo') {
            const { data } = await profileUserUpdate(this.baseInfo)
          } else if (this.editStatus === 'password') {
            const { data } = await profileUserChangePassword(this.password)
          } else {
            const { data } = await profileUserChangeEmail(this.email)
          }
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          UserModule.GetUserInfo()
        } catch (error) {
          console.error(error)
        } finally {
          this.editStatus = ''
        }
      }
    })
  }
  private resetData() {
    this.baseInfo = {
      username: '',
      mobile: '',
      remark: ''
    }
    this.password = {
      old_password: '',
      new_password: '',
      retype_password: ''
    }
    this.email = {
      email: ''
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .edit-content {
    .update-button {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
